//
//  MainViewCtr.m
//  DoNotRemember
//
//  Created by Jinniu on 2019/1/30.
//  Copyright © 2019年 Jinniu. All rights reserved.
//

#import "MainViewCtr.h"
#import "MainViewCtrCell.h"
#import "AddRecordVC.h"
#import "MainViewCtrModel.h"
#import "HXSearchBar.h"
@interface MainViewCtr ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>{
    int _page;
    NSMutableArray * _dataArr;
}
@property(nonatomic,strong)UITableView * myTab;
@end

@implementation MainViewCtr

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    _dataArr = [NSMutableArray new];
    [self createRightBtn];
    [self createSearchBar];
    [self.view addSubview:self.myTab];
    [self getData:YES];
}
-(void)getData:(BOOL)isShowHud{
    if (isShowHud) {
        [FTIndicator showProgressWithMessage:@"加载中"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:0.5];
    }
    NSArray * arr = [MainViewCtrModel bg_find:MainViewCtrTab range:NSMakeRange(_page*50+1,50) orderBy:nil desc:YES];
    [_dataArr addObjectsFromArray:arr];
    [_myTab.mj_header endRefreshing];
    [_myTab.mj_footer endRefreshing];
    [_myTab reloadData];
}
-(void)dismiss{
    [FTIndicator dismissProgress];
}
-(void)createSearchBar{
    UIView * bgViwe = [[UIView alloc]initWithFrame:Frame(0, kTopHeight, IPHONE_WIDTH, 40)];
    bgViwe.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgViwe];
    HXSearchBar *searchBar = [[HXSearchBar alloc] initWithFrame:CGRectMake(10, 0, IPHONE_WIDTH - 20, 40)];
    searchBar.backgroundColor = [UIColor clearColor];
    searchBar.delegate = self;
    //输入框提示
    searchBar.placeholder = @"搜索";
    //TextField
    searchBar.searchBarTextField.layer.cornerRadius = 4;
    searchBar.searchBarTextField.layer.masksToBounds = YES;
    searchBar.searchBarTextField.layer.borderColor = ThemeColor.CGColor;
    searchBar.searchBarTextField.layer.borderWidth = 1.0;
    //清除按钮图标
    searchBar.clearButtonImage = [UIImage imageNamed:@"删除"];
    //去掉取消按钮灰色背景
    searchBar.hideSearchBarBackgroundImage = YES;
    [bgViwe addSubview:searchBar];
}
//已经开始编辑时的回调
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    HXSearchBar *sear = (HXSearchBar *)searchBar;
    sear.cancleButton.backgroundColor = [UIColor clearColor];
    [sear.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [sear.cancleButton setTitleColor:ThemeColor forState:UIControlStateNormal];
    sear.cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];
}
//编辑文字改变的回调
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length==0) {
        [_dataArr removeAllObjects];
        [self getData:NO];
    }
}
//搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM MainViewControllerTab WHERE BG_title LIKE '%%%@%%' OR BG_tagStr LIKE '%%%@%%' OR BG_category LIKE '%%%@%%'",searchBar.text,searchBar.text,searchBar.text];
    NSArray * arr = bg_executeSql(sql, MainViewCtrTab, [MainViewCtrModel class]);
    if (_dataArr.count!=0) {
        [_dataArr removeAllObjects];
    }
    [self.view endEditing:YES];
    [_dataArr addObjectsFromArray:arr];
    [_myTab reloadData];
}
//取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    [self.view endEditing:YES];
    [_dataArr removeAllObjects];
    [self getData:NO];
}

-(void)createRightBtn{
    UIButton * rightBtn = [[UIButton alloc]initWithFrame:Frame(IPHONE_WIDTH-100, 0, 40, kNavBarHeight)];
    [rightBtn setImage:Image(@"选择按钮") forState:0];
    UIBarButtonItem * rightItme = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItme;
    [rightBtn addTarget:self action:@selector(rightNavBtnClick) forControlEvents:UIControlEventTouchUpInside];
}
-(void)rightNavBtnClick{
    AddRecordVC * vc = [AddRecordVC new];
    vc.refreshBlock = ^{
        [self.myTab.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MainViewCtrCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[MainViewCtrCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    MainViewCtrModel * mo = _dataArr[indexPath.row];
    cell.model = mo;
    cell.accountBlock = ^{
        UIPasteboard * board = [UIPasteboard generalPasteboard];
        board.string = mo.account;
        [Mytools warnText:@"复制成功" status:Success];
    };
    cell.passBlock = ^{
        UIPasteboard * board = [UIPasteboard generalPasteboard];
        board.string = mo.password;
        [Mytools warnText:@"复制成功" status:Success];
    };
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除啦";
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    MainViewCtrModel * mo = _dataArr[indexPath.row];
    [_dataArr removeObjectAtIndex:indexPath.row];    
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(bg_primaryKey),mo.bg_id];
    [MainViewCtrModel bg_delete:MainViewCtrTab where:where];
    [tableView reloadData];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MainViewCtrModel * mo = _dataArr[indexPath.row];
    AddRecordVC * vc = [AddRecordVC new];
    vc.refreshBlock = ^{
        [self.myTab.mj_header beginRefreshing];
    };
    vc.model = mo;
    [self.navigationController pushViewController:vc animated:YES];
}
-(UITableView*)myTab{
    if (_myTab == nil) {
        _myTab = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight+40, IPHONE_WIDTH, IPHONE_HEIGHT-kTabbarHeight-kTopHeight-40) style:UITableViewStyleGrouped];
        _myTab.delegate = self;
        _myTab.dataSource = self;
        _myTab.rowHeight = 100;
        _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self->_page = 0;
            [self->_dataArr removeAllObjects];
            [self getData:YES];
        }];
        _myTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self->_page ++;
            [self getData:YES];
        }];
    }
    return _myTab;
}
@end
